<template>
  <div>
    <span>{{ state.value }}{{ state.suffix }}</span>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, watch } from "vue";

const props = defineProps({
  maxValue: Number,
  minValue: Number,
  suffix: String,
  modelValue: Number,
  thousands: {
    type: Boolean,
    default: "",
  },
  //已什么为单位
  unit: {
    type: String,
    default: "",
  },
  symbol: {
    type: String,
    default: "",
  },
  //保留小位数
  decimalDigits: {
    type: Number,
    default: 2,
  },
  //位置
  position: {
    type: String,
    default: "left",
  },
});

const state = reactive({
  value: "",
  thousands: true,
  suffix: "",
});

const numberToCurrencyNo = (value: any) => {
  if (value == "-" || value == "NaN" || value == "undefined") return "-";
  value = (Math.round(value * 100) / 100).toFixed(props.decimalDigits) + "";
  // 获取整数部分
  const intPart = Math.trunc(value);
  let num;
  const dataValue = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
  if (Object.is(intPart, -0)) {
    num = "-" + dataValue;
  } else {
    num = intPart;
  }
  // 整数部分处理，增加,
  const intPartFormat = num;
  // 预定义小数部分
  let floatPart = "";
  // 将数值截取为小数部分和整数部分
  const valueArray = value.toString().split(".");
  if (valueArray.length === 2) {
    // 有小数部分
    floatPart = valueArray[1].toString(); // 取得小数部分
    if (intPartFormat == "-0" && floatPart == "00") {
      return "0" + "." + floatPart;
    }
    return intPartFormat + "." + floatPart;
  }
  return intPartFormat + floatPart;
};

const init = (): void => {
  state.suffix = props.suffix;
  if (props.unit != "" && props.unit != null) {
    let unitObj = {
      //以万元为单位
      W: 1,
      //以亿元单位
      Y: 100000000,
    };

    state.value = (
      props.modelValue / unitObj[props.unit.toUpperCase()]
    ).toFixed(props.decimalDigits);

    if (props.thousands) {
      state.value = numberToCurrencyNo(state.value);
    }
  } else {
    state.value = numberToCurrencyNo(props.modelValue);
  }

  if (
    props.position.toLowerCase() == "left" ||
    props.position.toLowerCase() == "l"
  ) {
    state.value = props.symbol + state.value;
  } else if (
    props.position.toLowerCase() == "right" ||
    props.position.toLowerCase() == "r"
  ) {
    state.value = state.value + props.symbol;
  }

  state.value = `${state.value}`;
  //positive,negative
};
watch(
  () => props.modelValue,
  (n, o) => {
    init();
  }
);
onMounted(() => {
  init();
});
</script>
